package org.saxonextensions.eml.emitter;

import org.saxonextensions.eml.emitter.AbstractEmailEmitter;
import org.saxonextensions.eml.emitter.MailSessionFactory;
import net.sf.saxon.trans.XPathException;
import net.sf.saxon.type.ValidationException;

import javax.mail.Session;
import java.util.Properties;
import java.util.logging.Level;

/**
 * SMTP Emitter, immideately dispath received message.
 * Uses SMTP Pool
 * TODO Emitter does not work 
 *
 * @author Ivan Latysh IvanLatysh@yahoo.ca
 * @since 21-Jun-2004 8:05:04 PM
 */
public class SMTPEmitter extends AbstractEmailEmitter {

  // smtp host property
  public static final String SMTP_HOST = "{http://saxonextensions.org/email}smtp-host";
  /** smtp sending threads */
  public static final String SMTP_POOL_SIZE = "{http://saxonextensions.org/email}smtp-threads";

  /**
   * Start document and read config parameters
   *
   * @param properties properties count
   * @throws XPathException when unable to start the document
   */
  public void startDocument(int properties) throws XPathException {
    try {
      // get output properties
      Properties outProps = getOutputProperties();
      // get smtp host
      String smtpHost = outProps.getProperty(SMTP_HOST);
      // smtp threads
      if (null!=outProps.getProperty(SMTP_POOL_SIZE)) {
        // TODO FIXME
//        EMLDispatcherPool.getInstance().setMaxSize(Integer.valueOf(outProps.getProperty(SMTP_POOL_SIZE)));
      }
      // configure SessionFactory
      Properties props = MailSessionFactory.getInstance().getProps();
      if (null!=smtpHost) props.setProperty("mail.smtp.host", smtpHost);
      if (null!=smtpHost) props.setProperty("mail.debug", String.valueOf(logger.isLoggable(Level.FINEST)));
      MailSessionFactory.getInstance().setProps(props);
      // create a new SMTP Session
      session = MailSessionFactory.getSession();
    } catch (Exception e) {
      throw new ValidationException("Error reading email output properties.", e);
    }

    super.startDocument(properties);
  }

  /**
   * Handle the message message
   */
  protected void messageReceived() {
    try {
      // TODO FIXME
//      EMLDispatcherPool.getInstance().getDispather().dispatch(message);
    } catch (Exception e) {
      logger.log(Level.SEVERE, "Can't send the message.", e);
    }
  }

  protected Session getSession() throws Exception {
    return MailSessionFactory.getSession();
  }

}
